package it.illumedellaragione.googlecalendar;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class ManageDate {

	public static Date nextDate(Date countFrom,String freqUnit, int frequency) throws Exception{

	    Date retDate = null;

	    if (countFrom == null) {
	      return retDate;
	    }

	    if (freqUnit.equals("DAYS"))
	    {
	      Calendar c = Calendar.getInstance();
	      c.setTime(countFrom);
	      c.add(5, frequency);
	      retDate = c.getTime();
	    }
	    else if (freqUnit.equals("WEEKS"))
	    {
	      Calendar c = Calendar.getInstance();
	      c.setTime(countFrom);
	      c.add(5, frequency * 7);
	      retDate = c.getTime();
	    }
	    else if (freqUnit.equals("MONTHS"))
	    {
	      retDate = addMonths(frequency, countFrom);
	    }
	    else if (freqUnit.equals("YEARS"))
	    {
	      retDate = addYears(frequency, countFrom);
	    }

	    return retDate;
	}

	protected static Date addMonths(int addMonths, Date fromDate)
	    throws Exception
	  {
	    GregorianCalendar cm = new GregorianCalendar();
	    cm.setTime(fromDate);

	    int fromDay = cm.get(5);
	    cm.set(5, 1);

	    cm.add(2, addMonths);

	    int resultingMonth = cm.get(2);

	    cm.add(5, fromDay - 1);

	    while (cm.get(2) != resultingMonth)
	    {
	      cm.add(5, -1);
	    }

	    return cm.getTime();
	  }

	protected static Date addYears(int addYears, Date fromDate)
	  {
	    GregorianCalendar cy = new GregorianCalendar();
	    cy.setTime(fromDate);

	    boolean fromLeapYearDay = (cy.get(5) == 29) && (cy.get(2) == 2);

	    cy.add(1, addYears);

	    if ((fromLeapYearDay) && (cy.get(5) != 29))
	    {
	      cy.add(5, -1);
	    }

	    return cy.getTime();
	  }



}
